/*
 * Copyright 2007-2008 Andrew O'Malley
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package ws.quokka.plugin.script;

import org.apache.tools.ant.util.ScriptRunnerBase;
import org.apache.tools.ant.util.ScriptRunnerHelper;

import ws.quokka.core.plugin_spi.support.AbstractPlugin;
import ws.quokka.core.plugin_spi.support.Setter;

import java.io.File;


/**
 *
 */
public class ScriptPlugin extends AbstractPlugin {
    //~ Methods --------------------------------------------------------------------------------------------------------

    public void javascript() {
        script();
    }

    public void script() {
        ScriptRunnerHelper helper = new ScriptRunnerHelper();
        helper.setProjectComponent(getProject().createTask("echo")); // Component that gets bound to "self"
        helper.setClasspath(getResources().getPathGroupAsPath("script"));

        Setter setter = new Setter(properties());
        setter.set(helper, new String[] { "language", "manager", "setBeans", "src" });

        String script = properties().getString("script", null);
        File src = properties().getFile("src", null);
        assertTrue(((script == null) && (src != null)) || ((script != null) && (src == null)),
            "Either the 'src' or 'script' must be set (but not both)");

        if (script != null) {
            helper.addText(script);
        }

        ScriptRunnerBase runner = helper.getScriptRunner();
        runner.addBean("quokka", getProject().getReference("q.project.scriptHelper"));
        runner.executeScript("ANT");
    }
}
